package com.chungkui.check.expression.impl;

import com.chungkui.check.core.Constants;
import com.chungkui.check.core.bean.CheckResult;
import com.chungkui.check.expression.BaseExpression;
import com.chungkui.check.handler.insidecheck.InsideType;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.util.Map;

/**
 * @Author: jason
 * @Date: 2020/5/22 14:33
 * @Version 1.0
 */
public class DateIntervalMatchExpression extends BaseExpression {
    private String start;
    private String end;
    private String code;
    private Boolean require;
    private String fmt;
    private Long maxInterval;
    private Long minInterval;

    @Override
    public CheckResult match(Map<String, Object> params) {
        String startv = MapUtils.getString(params, this.start);
        String endv = MapUtils.getString(params, this.end);
        if (require != null && require && (StringUtils.isEmpty(startv) || StringUtils.isEmpty(endv))) {
            return CheckResult.fail(this.code,MapUtils.getString(this.msg, Constants.NULL));
        }
        if (StringUtils.isNotEmpty(startv) && StringUtils.isNotEmpty(endv)) {
            DateTimeFormatter formatter = DateTimeFormat.forPattern(this.fmt);
            DateTime startTime = DateTime.parse(startv, formatter);
            DateTime endTime = DateTime.parse(endv, formatter);
            if (maxInterval != null && startTime.plus(maxInterval).isBefore(endTime)) {
                return CheckResult.fail(this.code,MapUtils.getString(this.msg, "maxInterval"));
            }
            if (minInterval != null && startTime.plus(minInterval).isAfter(endTime)) {
                return CheckResult.fail(this.code,MapUtils.getString(this.msg, "minInterval"));
            }
        }
        return CheckResult.success();
    }

    @Override
    public void compile(Map<String, Object> config) {
        this.fmt = org.apache.commons.collections4.MapUtils.getString(config, "fmt");
        this.require = MapUtils.getBoolean(config, "require", true);
        this.start = MapUtils.getString(config, "start");
        this.end = MapUtils.getString(config, "end");
        this.code = MapUtils.getString(config, "code");
        this.maxInterval = MapUtils.getLong(config, "maxInterval");
        this.minInterval = MapUtils.getLong(config, "minInterval");
    }


    @Override
    public InsideType getInsideType() {
        return InsideType.NO_INSISE;
    }
}
